<template>
  <transition name="yy-message-fade" :appear="true" @after-leave="handleAfterLeave">
    <div v-show="visible" role="alert" @mouseenter="stopShowTimer" @mouseleave="startShowTimer"
         :style="{
          ...customClass,
          top:`${verticalOffset}px`
        }" :class="[
        'yy-message',
        `yy-message--${type}`,
        {'is-closable':showClose},
        {'is-center':center}]">
      <i v-if="iconClass" :class="['yy-message_icon', 'iconfont', iconClass]"></i>
      <i v-else :class="['yy-message_icon', 'iconfont', `icon-${type}`]"></i>
      <slot>
        <span v-if="!dangerouslyUseHTMLString" class="yy-message__content">{{message}}</span>
        <span v-else class="yy-message__content" v-html="message"></span>
      </slot>
      <i v-if="showClose" class="yy-message_closeBtn iconfont icon-close" @click="close"></i>
    </div>
  </transition>
</template>

<script>
export default {
  name: 'YYMessage',
  components: {},
  props: {},
  data () {
    return {
      message: '',
      visible: true,
      duration: 3000,
      timer: null,
      showClose: false,
      type: 'info',
      center: false,
      dangerouslyUseHTMLString: false,
      iconClass: '',
      customClass: {},
      verticalOffset: 20,
      offset: 20,
      onClose: () => { },
    }
  },
  methods: {
    // 弹出消息
    startShowTimer () {
      if (this.duration > 0) {
        this.timer = setTimeout(() => {
          this.close()
        }, this.duration)
      }
    },
    // 鼠标移入时停止定时器
    stopShowTimer () {
      clearTimeout(this.timer);
    },
    close () {
      this.onClose()
      this.visible = false
      this.stopShowTimer();
    },
    handleAfterLeave () {
      // 销毁组件,注意销毁组件不代表 dom 结构就也销毁了
      this.$destroy()
      // 把 dom 结构从页面中移除
      this.$el.parentNode.removeChild(this.$el)
    }
  },
  created () { },
  mounted () {
    this.startShowTimer()
  }
}
</script>
<style lang="less" scoped>
@import "./index.css";
</style>